package com.supor.aiot.common.helper;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.android.baseconfig.base.RxBus3;
import com.android.baseconfig.common.helper.PermissionsChecker;
import com.android.baseconfig.common.utils.DialogUtils;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.common.utils.Util;
import com.android.baseconfig.constact.AppGlobalHost;
import com.cmic.sso.sdk.AuthThemeConfig;
import com.cmic.sso.sdk.auth.AuthnHelper;
import com.cmic.sso.sdk.auth.LoginClickListener;
import com.cmic.sso.sdk.auth.TokenListener;
import com.supor.aiot.common.R;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.app.api.UserImpl;
import com.supor.aiot.common.arouter.PathUrl;
import com.supor.aiot.common.interfaces.CustomClickListener;
import com.supor.aiot.common.ui.activity.SuporPermissionActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: CmccHelper <br>
 * 作者: lei <br>
 * 日期: 2020/11/5 <br>
 */
public class CmccHelper implements TokenListener {

    private static final String TAG = "CmccHelper";
    private Context context;
    private AuthnHelper mAuthnHelper;
    private AuthThemeConfig.Builder themeConfigBuilder;
    private static final int CMCC_SDK_REQUEST_GET_PHONE_INFO_CODE = 1111;
    private static final int CMCC_SDK_REQUEST_MOBILE_AUTH_CODE = 2222;
    private static final int CMCC_SDK_REQUEST_LOGIN_AUTH_CODE = 3333;
    private String mAccessToken;
    private AlertDialog alertDialog;
    private Dialog dialog;
    private String loginTips;
    private String host;
    int mobileType;
    /**
     * 手机屏幕宽，单位dp
     */
    int widthDp;
    /**
     * 手机屏幕高，单位dp
     */
    int heightDp;
    /**
     * 手机状态栏高，单位dp
     */
    int statusBarDp;
    /**
     * 手机导航栏高，单位dp
     */
    int navigationBarDp;
    /**
     * 自定义布局bottomMargin，单位dp，区分小屏和大屏
     */
    int offsetY;
    int middleYDp;
    int count = 0;
    boolean isFullModel = true;
    //震动
    private Vibrator vibrator;


    public CmccHelper(Context context) {
        this.context = context;
        mobileType = Util.getMobileType(context);
        widthDp = (int) (AppAgent.getScreenWidth() / AppAgent.density);
        statusBarDp = Util.px2dip(context, SystemUtils.getDefaultStatusHeight(context));
        loginTips = context.getResources().getString(R.string.cmcc_login_alert);
        ThreadUtils.execute(this::init);
        //震动
        vibrator = (Vibrator) AppAgent.getApp().getSystemService(Service.VIBRATOR_SERVICE);
    }

    public void init() {
        Logc.d("CmccHelper: mobileType= " + mobileType);
        // Logc.d("CmccHelper: heightDp= " + heightDp);
        // Logc.d("CmccHelper: statusBarDp= " + statusBarDp);
        // Logc.d("CmccHelper: navigationBarDp= " + Util.px2dip(context, SystemUtils.getNavigationHeight(context)));
        initSDK();
        preGetPhone();
    }

    private void preGetPhone() {
        ThreadUtils.execute(() -> {
            while (count++ < 3) {
                ThreadUtils.execute(this::getPhoneInfo);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            count = 0;
        }, 300);
    }

    private void initSDK() {
        Logc.d(TAG, System.currentTimeMillis() + " ");

        host = AppGlobalHost.getHost();
        mAuthnHelper = AuthnHelper.getInstance(context);
        mAuthnHelper.setOverTime(3000);
        mAuthnHelper.setPageInListener((resultCode, jsonObj) -> {
            // 200087 init success
            Logc.d("initSDK", "resultCode: " + resultCode);
        });
        initView();
    }

    /**
     * 半屏模式
     *
     * @param authPageActIn
     * @param activityOut
     * @param activityIn
     * @param authPageActOut
     */
    private void initView(String authPageActIn, String activityOut, String activityIn, String authPageActOut) {
        navigationBarDp = Util.px2dip(context, SystemUtils.getNavigationHeight(context));
        navigationBarDp = (AppAgent.isNavigationBarExist ? navigationBarDp : 0);
        heightDp = getSize(R.dimen.dp_365) + navigationBarDp;
        middleYDp = (heightDp - statusBarDp - offsetY - navigationBarDp) / 2;
        RelativeLayout relativeLayout = new RelativeLayout(context);
        relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        View layout = LayoutInflater.from(context).inflate(R.layout.empty_layout, relativeLayout,
                false);
        themeConfigBuilder = new AuthThemeConfig.Builder()
                .setStatusBar(0x00ffffff, false)//状态栏颜色、字体颜色
                .setAuthContentView(layout)

                .setClauseLayoutResID(R.layout.title_layout, "returnId")//设置服务条款标题布局资源文件ID（包括返回按钮）
                .setNavTextSize(getSize(R.dimen.dp_22))
                .setNavTextColor(0xFF000000)//设置服务条款标题字体颜色
                .setNavColor(Color.BLACK) //设置服务条款标题颜色

                .setNumberSize(getSize(R.dimen.dp_17), true)////手机号码字体大小
                .setNumberColor(0xFF333333)//手机号码字体颜色
                .setNumberOffsetX(getSize(R.dimen.dp_31))//号码栏X偏移量
                .setNumFieldOffsetY(getSize(R.dimen.dp_116))

                .setLogBtnImgPath("umcsdk_login_btn_bg")//登录按钮背景
                .setLogBtnText(context.getString(R.string.cmcc_login_btn_text), 0xFFFFFFFF, getSize(R.dimen.dp_16), true)
                .setLogBtnOffsetY(getSize(R.dimen.dp_282))//登录按钮Y偏移量
                .setLogBtn(-1, getSize(R.dimen.dp_43))
                .setLogBtnMargin(getSize(R.dimen.dp_15), getSize(R.dimen.dp_15))
                .setCheckTipText(context.getString(R.string.cmcc_check_tip_text))
                .setBackPressedListener(() -> {
                    Logc.i("cmcc login back: 5");
                    RxBus3.getInstance().post(Constants.Tag.LOGIN, Constants.Value.CANCEL);
                })
                .setLogBtnClickListener(new LoginClickListener() {
                    @Override
                    public void onLoginClickStart(Context context, JSONObject jsonObj) {
                        showLoading(context, "", false);
                    }

                    @Override
                    public void onLoginClickComplete(Context context, JSONObject jsonObj) {
                        Logc.i(TAG, "onLoginClickComplete: ");
                    }
                })

                .setCheckBoxListener((context, jsonObject) -> {
                    boolean isPrivacyState = mAuthnHelper.getAuthThemeConfig().isPrivacyState();
                    if (!isPrivacyState) {
                        ToastUtils.getInstance().showCustomToast(context.getString(R.string.cmcc_check_tip_text));
                        if (vibrator == null) {
                            vibrator = (Vibrator) AppAgent.getApp().getSystemService(Service.VIBRATOR_SERVICE);
                        }
                        try {
                            vibrator.vibrate(VibrationEffect.createWaveform(new long[]{200, 200, 200, 200, 200, 200, 200},
                                    -1));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .setCheckBoxImgPath("slide_on", "slide_off",
                        getSize(R.dimen.dp_37), getSize(R.dimen.dp_20))
                .setPrivacyState(false)//授权页check

                .setPrivacyAlignment(
                        "请您阅读完整版" + "用户服务协议、隐私保护声明\n以及" + AuthThemeConfig.PLACEHOLDER,
                        "用户服务协议", host + Constants.USERSERVERAGREE, "隐私保护声明",
                        host + Constants.USERPRIVACYAGREE, null, null, null, null)
                .setPrivacyText(getSize(R.dimen.dp_12), 0xFF333333, 0xffC8C8C8, false, false)
                .setClauseColor(0xFF333333, 0xff16bf86)//条款颜色

                .setPrivacyMargin(getSize(R.dimen.dp_31), getSize(R.dimen.dp_0))
                .setPrivacyBookSymbol(false)
                .setPrivacyOffsetY(getSize(R.dimen.dp_186))//隐私条款Y偏移量
                .setCheckBoxLocation(1)
                .setAuthPageActIn(authPageActIn, activityOut)
                .setAuthPageActOut(activityIn, authPageActOut);

        themeConfigBuilder.setAuthPageWindowMode(widthDp, heightDp)
                .setWindowBottom(1)
                .setThemeId(R.style.LoginTheme);
        mAuthnHelper.setAuthThemeConfig(themeConfigBuilder.build());

        TextView otherWayLogin = layout.findViewById(R.id.tv_other_way);
        otherWayLogin.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick(View v) {
                ARouter.getInstance().build(PathUrl.PATH_DIALOG_LOGIN)
                        .withTransition(0, 0)
                        .navigation(context);
                quit();
            }
        });

        ImageView ivBack = layout.findViewById(R.id.iv_back);
        ivBack.setOnClickListener(v -> {
            quit();
            RxBus3.getInstance().post(Constants.Tag.LOGIN, Constants.Value.CANCEL);
        });
        TextView tvAuth = layout.findViewById(R.id.tv_auth);
        if (mobileType == 1) {
            tvAuth.setText("认证服务由中国移动提供");
        } else if (mobileType == 2) {
            tvAuth.setText("认证服务由中国联通提供");
        } else if (mobileType == 3) {
            tvAuth.setText("认证服务由中国电信提供");
        } else {
            tvAuth.setText("认证服务由中国移动提供");
        }
    }

    /**
     * 全屏模式
     */
    private void initView() {
        heightDp = (int) (AppAgent.heightPixels / AppAgent.density);
        navigationBarDp = Util.px2dip(context, SystemUtils.getNavigationHeight(context));
        navigationBarDp = (AppAgent.isNavigationBarExist ? navigationBarDp : 0);
        // offsetY是layout里bottomMargin，值为37dp
        offsetY = 37;
        // 内容中间线：内容高为屏幕高度去掉状态栏、导航栏和bottomMargin
        middleYDp = (heightDp - statusBarDp - offsetY - navigationBarDp) / 2;

        RelativeLayout relativeLayout = new RelativeLayout(context);
        relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        View layout = LayoutInflater.from(context).inflate(R.layout.empty_layout_full, relativeLayout,
                false);
        themeConfigBuilder = new AuthThemeConfig.Builder()
                .setStatusBar(0x00ffffff, true)//状态栏颜色、字体颜色
                .setAuthContentView(layout)

                .setClauseLayoutResID(R.layout.title_layout, "returnId")//设置服务条款标题布局资源文件ID（包括返回按钮）
                .setNavTextSize(getSize(R.dimen.dp_22))
                .setNavTextColor(0xFF000000)//设置服务条款标题字体颜色
                .setNavColor(Color.BLACK) //设置服务条款标题颜色

                .setNumberSize(getSize(R.dimen.dp_17), true)////手机号码字体大小
                .setNumberColor(0xFF333333)//手机号码字体颜色
                .setNumberOffsetX(getSize(R.dimen.dp_31))//号码栏X偏移量
                .setNumFieldOffsetY(middleYDp - 36 - 1 - 40 - 12)
                // (33=36-3)-协议栏一半高度|28-到协议栏的距离|24-号码栏text高度

                .setLogBtnImgPath("umcsdk_login_btn_bg")//登录按钮背景
                .setLogBtnText(context.getString(R.string.cmcc_login_btn_text), 0xFFFFFFFF, getSize(R.dimen.dp_16), true)
                .setLogBtnOffsetY(middleYDp + 36 +31)//登录按钮Y偏移量
                .setLogBtn(-1, getSize(R.dimen.dp_44))
                .setLogBtnMargin(getSize(R.dimen.dp_15), getSize(R.dimen.dp_15))
                .setCheckTipText(context.getString(R.string.cmcc_check_tip_text))
                .setBackPressedListener(() -> {
                    Logc.i("cmcc login back: 5");
                    RxBus3.getInstance().post(Constants.Tag.LOGIN, Constants.Value.CANCEL);
                })
                .setLogBtnClickListener(new LoginClickListener() {
                    @Override
                    public void onLoginClickStart(Context context, JSONObject jsonObj) {
                        showLoading(context, "", false);
                        Logc.e("onLoginClickStart: " + mAuthnHelper.getAuthThemeConfig().isPrivacyState());
                    }

                    @Override
                    public void onLoginClickComplete(Context context, JSONObject jsonObj) {
                        Logc.i(TAG, "onLoginClickComplete: ");
                    }
                })

                .setCheckBoxListener((context, jsonObject) -> {
                    boolean isPrivacyState = mAuthnHelper.getAuthThemeConfig().isPrivacyState();
                    if (!isPrivacyState) {
                        ToastUtils.getInstance().showCustomToast(context.getString(R.string.cmcc_check_tip_text));
                        if (vibrator == null) {
                            vibrator = (Vibrator) AppAgent.getApp().getSystemService(Service.VIBRATOR_SERVICE);
                        }
                        try {
                            vibrator.vibrate(VibrationEffect.createWaveform(new long[]{200, 200, 200, 200, 200, 200, 200},
                                    -1));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .setCheckBoxImgPath("slide_on", "slide_off",
                        getSize(R.dimen.dp_37), getSize(R.dimen.dp_20))
                .setPrivacyState(false)//授权页check

                .setPrivacyAlignment(
                        "请您阅读完整版" + "用户服务协议、隐私保护声明\n以及" + AuthThemeConfig.PLACEHOLDER,
                        "用户服务协议", host + Constants.USERSERVERAGREE, "隐私保护声明",
                        host + Constants.USERPRIVACYAGREE, null, null, null, null)
                .setPrivacyText(getSize(R.dimen.dp_12), 0xff333333, 0xffC8C8C8, false, false)
                .setClauseColor(0xff333333, 0xff16bf86)//条款颜色

                .setPrivacyMargin(getSize(R.dimen.dp_30), getSize(R.dimen.dp_0))
                .setPrivacyBookSymbol(false)
                // .setPrivacyOffsetY_B(getSize(R.dimen.dp_55))//隐私条款Y偏移量
                .setPrivacyOffsetY(middleYDp - 20)//隐私条款Y偏移量
                .setCheckBoxLocation(1)
                .setAuthPageActIn("activity_open_enter","activity_open_exit")
                .setAuthPageActOut("activity_close_enter","activity_close_exit");

        themeConfigBuilder.setAuthPageWindowMode(0, 0)
                .setThemeId(R.style.CmccLoginThemeFull);
        mAuthnHelper.setAuthThemeConfig(themeConfigBuilder.build());
        TextView otherWayLogin = layout.findViewById(R.id.tv_other_way);
        otherWayLogin.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick(View v) {
                ARouter.getInstance().build(PathUrl.PATH_LOGIN)
                        .withTransition(com.android.baseconfig.R.anim.activity_open_enter,
                                com.android.baseconfig.R.anim.activity_open_exit)
                        .navigation(context);
                quit();
            }
        });
        ImageView ivBack = layout.findViewById(R.id.iv_back);
        ivBack.setOnClickListener(v -> quit());
        TextView tvAuth = layout.findViewById(R.id.tv_auth);
        if (mobileType == 1) {
            tvAuth.setText("认证服务由中国移动提供");
        } else if (mobileType == 2) {
            tvAuth.setText("认证服务由中国联通提供");
        } else if (mobileType == 3) {
            tvAuth.setText("认证服务由中国电信提供");
        } else {
            tvAuth.setText("认证服务由中国移动提供");
        }
    }

    private int getSize(int dimen) {
        return Util.px2dip(context, context.getResources().getDimensionPixelSize(dimen));
    }

    public void showLoading(Context context, String tips, boolean isCanCancel) {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
            dialog = null;
        }
        dialog = DialogUtils.createLoadingDialog(context, tips);
        dialog.setOnKeyListener((dialog, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_UP) {
                dialog.dismiss();
            }
            return keyCode == KeyEvent.KEYCODE_BACK;
        });
        dialog.setCancelable(isCanCancel);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.show();
    }

    public void closeLoading() {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    /*private void dismissDialog() {
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
            alertDialog = null;
        }
    }*/

    @SuppressLint("CheckResult")
    @Override
    public void onGetTokenComplete(int SDKRequestCode, JSONObject jObj) {
        if (jObj == null) {
            return;
        }
        try {
            //调用方式不传SDKRequestCode时，该值默认为：-1
            Logc.i(TAG, "Code: " + SDKRequestCode + " : " + jObj);
            if (SDKRequestCode == CMCC_SDK_REQUEST_LOGIN_AUTH_CODE) {
                if (jObj.has("token")) {
                    mAccessToken = jObj.optString("token");
                    HashMap<String, String> map = new HashMap<>(2);
                    map.put("token", mAccessToken);
                    UserImpl.getInstance().cmccLogin(mAccessToken)
                            .subscribe(result -> {
                                closeLoading();
                                // Logc.e("login: " + result.toString());
                                if (result.isSuccess()) {
                                    SuporPresenter.getInstance().saveInfo(result.data, true);
                                    RxBus3.getInstance().post(Constants.Tag.LOGIN, Constants.Value.SUCCESS);
                                    quit();
                                } else {
                                    ToastUtils.getInstance().showCustomToast(String.format(loginTips,
                                            result.message));
                                }
                                AppAgent.isShowCmcc = false;

                            }, e -> {
                                Logc.e("login: " + e.getMessage());
                                closeLoading();
                                ToastUtils.getInstance().showCustomToast(String.format(loginTips,
                                        e.getMessage()));
                                AppAgent.isShowCmcc = false;
                            });

                } else {
                    String code = (String) jObj.get("resultCode");
                    if ("200002".equalsIgnoreCase(code) || "200048".equalsIgnoreCase(code)) {
                        // 无法识别sim卡或没有sim卡
                        // ToastUtils.getInstance().showCustomToast(String.format(loginTips, "无法识别sim" +
                        //         "卡或没有sim卡"));
                        closeLoading();
                        SuporPresenter.getInstance().otherLogin(context, isFullModel);
                    } else if ("200023".equalsIgnoreCase(code)) {
                        // 请求超时
                        // loginFailed();
                        closeLoading();
                        SuporPresenter.getInstance().otherLogin(context, isFullModel);
                    } else if ("102507".equalsIgnoreCase(code)) {
                        // 登录超时（授权页点登录按钮时）
                        loginFailed();
                    } else if ("200022".equalsIgnoreCase(code)) {
                        // 未检测到网络
                        // SuporPresenter.getInstance().otherLogin(context);
                        // ToastUtils.getInstance().showCustomToast(String.format(loginTips, "未检测到网络"));
                        loginFailed();
                    } else if ("200027".equalsIgnoreCase(code)) {
                        // 未开启数据网络或网络不稳定
                        // SuporPresenter.getInstance().otherLogin(context);
                        // ToastUtils.getInstance().showCustomToast(String.format(loginTips, "无数据网络"));
                        loginFailed();
                    } else if ("200028".equalsIgnoreCase(code)) {
                        // 网络异常
                        // SuporPresenter.getInstance().otherLogin(context);
                        // ToastUtils.getInstance().showCustomToast(String.format(loginTips, "网络异常"));
                        loginFailed();
                    } else if ("200039".equalsIgnoreCase(code)) {
                        // 异网取号网关取号失败
                        loginFailed();
                    } else if (!"200020".equalsIgnoreCase(code) && !"103000".equalsIgnoreCase(code)) {
                        // ToastUtils.getInstance().showCustomToast(String.format(loginTips, "异常"));
                        loginFailed();
                    }
                    AppAgent.isShowCmcc = false;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
            loginFailed();
            AppAgent.isShowCmcc = false;
        }
    }

    private void loginFailed() {
        closeLoading();
        ToastUtils.getInstance().showCustomToast("一键登录失败，请通过手机号验证码登录。");
        if (!"LoginAuthActivity".equalsIgnoreCase(AppAgent.getCurrentActivity().getClass().getSimpleName())) {
            SuporPresenter.getInstance().otherLogin(context, isFullModel);
        }
    }

    public void quit() {
        if (mAuthnHelper != null) {
            mAuthnHelper.quitAuthActivity();
            // SuporPresenter.getInstance().otherLogin(5, "");
        }
    }

    /**
     * 显示一键登录
     *
     * @param isFull 是否全屏显示
     */
    public void displayLogin(boolean isFull) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PermissionsChecker mPermissionsChecker = new PermissionsChecker(context);
            if (mPermissionsChecker.lacksPermissions(Manifest.permission.READ_PHONE_STATE)) {
                ArrayList<String> list = new ArrayList<>();
                list.add(Manifest.permission.READ_PHONE_STATE);

                Intent intent = new Intent(AppAgent.getCurrentActivity(),
                        SuporPermissionActivity.class);
                intent.putStringArrayListExtra(Constants.Key.param_list, list);
                intent.putExtra(Constants.Key.param_params, isFull ? 1 : 4);
                intent.putExtra(Constants.Key.param_type, 3);
                AppAgent.getCurrentActivity().startActivity(intent);
            } else {
                AppAgent.isShowCmcc = true;
                if (isFull) {
                    if (!isFullModel) {
                        isFullModel = true;
                        initView();
                    }
                } else {
                    if (isFullModel) {
                        isFullModel = false;
                        initView("dialog_slide_in_bottom","dialog_slide_out_bottom",
                                "dialog_slide_in_bottom","dialog_slide_out_bottom");
                    }
                }
                mAuthnHelper.loginAuth(Constants.CMCC.APP_ID, Constants.CMCC.APP_KEY, this,
                        CMCC_SDK_REQUEST_LOGIN_AUTH_CODE);
            }
        } else {
            AppAgent.isShowCmcc = true;
            if (isFull) {
                if (!isFullModel) {
                    isFullModel = true;
                    initView();
                }
            } else {
                if (isFullModel) {
                    isFullModel = false;
                    initView("dialog_slide_in_bottom","dialog_slide_out_bottom",
                            "dialog_slide_in_bottom","dialog_slide_out_bottom");
                }
            }
            mAuthnHelper.loginAuth(Constants.CMCC.APP_ID, Constants.CMCC.APP_KEY, this,
                    CMCC_SDK_REQUEST_LOGIN_AUTH_CODE);
        }
        // SuporPresenter.getInstance().reportVideoControl(2);
    }

    public void displayLogin() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PermissionsChecker mPermissionsChecker = new PermissionsChecker(context);
            if (mPermissionsChecker.lacksPermissions(Manifest.permission.READ_PHONE_STATE)) {
                ArrayList<String> list = new ArrayList<>();
                list.add(Manifest.permission.READ_PHONE_STATE);

                Intent intent = new Intent(AppAgent.getCurrentActivity(),
                        SuporPermissionActivity.class);
                intent.putStringArrayListExtra(Constants.Key.param_list, list);
                intent.putExtra(Constants.Key.param_params, 1);
                intent.putExtra(Constants.Key.param_type, 3);
                AppAgent.getCurrentActivity().startActivity(intent);
            } else {
                AppAgent.isShowCmcc = true;
                mAuthnHelper.loginAuth(Constants.CMCC.APP_ID, Constants.CMCC.APP_KEY, this,
                        CMCC_SDK_REQUEST_LOGIN_AUTH_CODE);
            }
        } else {
            AppAgent.isShowCmcc = true;
            mAuthnHelper.loginAuth(Constants.CMCC.APP_ID, Constants.CMCC.APP_KEY, this,
                    CMCC_SDK_REQUEST_LOGIN_AUTH_CODE);
        }
    }

    public void mobileAuth() {
        mAuthnHelper.mobileAuth(Constants.CMCC.APP_ID, Constants.CMCC.APP_KEY, this,
                CMCC_SDK_REQUEST_MOBILE_AUTH_CODE);
    }

    public void getPhoneInfo() {
        ThreadUtils.execute(() -> mAuthnHelper.getPhoneInfo(Constants.CMCC.APP_ID, Constants.CMCC.APP_KEY, CmccHelper.this,
                CMCC_SDK_REQUEST_GET_PHONE_INFO_CODE));

    }

}
